<?php

App::uses('AppController', 'Controller');

class ProizvodiController extends AppController {
	
	public $uses = array('Product', 'Headphoto');
	
	public $paginate = array(
		'limit' => LIST_ITEMS_PER_PAGE
	);
	
	public function index() {
		$categories = $this->Product->Category->find('all', array(
		  'recursive' => false,
		  'conditions' => array( 'Category.parent_id' => null)
        ));
		$this->set(compact('categories'));
		
		if($photo = $this->Headphoto->find("first", array("conditions"=>array("entity"=>"Proizvodi","entity_id"=>"")))) {
			$this->top_photo = $photo['Headphoto']['image'];
		}
	}
	
	public function category() {
		$this->breadcrumbsAdd('Proizvodi', '/proizvodi');
		
		$category_key = $this->request->params['key'];
		$category = $this->Product->Category->find('first', array(
		  'conditions' => array('Category.key' => $category_key),
		  'fields'     => array('Category.id', 'Category.name', 'Category.description', 'ParentCategory.*'),
          'recursive' => 0
        ));
        
		if($photo = $this->Headphoto->find("first", array("conditions"=>array("entity"=>"Proizvodi","entity_id"=>$category_key)))) {
			$this->top_photo = $photo['Headphoto']['image'];
		}
		if($category) {
	        $parent = $category['ParentCategory'];
		    if ($parent['id']) {
		        $this->breadcrumbsAdd($parent['name'], '/proizvodi/'.$parent['key']);
		    }
		    $this->breadcrumbsAdd($category['Category']['name']);
            
            $category['SubCategory'] = Set::extract($this->Product->Category->find('all', array(
                'conditions' => array('Category.parent_id' => $category['Category']['id']),
                'recursive'  => 0
            )), '{n}.Category');
			
			$products = $this->paginate('Product', array('Product.category_id'=>$category['Category']['id']));
			
			$this->set(compact('category', 'products'));
		}else{
			$this->redirect("/proizvodi");
		}
	}
	
	public function proizvod($id) {
		$product = $this->Product->findById($id);
		$this->breadcrumbsAdd('Proizvodi', '/proizvodi');
		$this->breadcrumbsAdd($product['Category']['name'], '/proizvodi/'.$product['Category']['key']);
		$this->breadcrumbsAdd($product['Product']['name']);
		
		// receipes
		if(!empty($product['Receipe'])) {
			foreach($product['Receipe'] as &$receipe) {
				$receipe = $this->Product->Receipe->findById($receipe['id']);
			}
		}
		
		// related products
		$related_products = $this->Product->find("all", array(
			"fields" => array("Product.id", "Product.name"),
			"conditions" => array( 
				"Product.category_id" => $product['Product']['category_id'],
				"Product.id !=" => $id
			),
			"order" => "RAND()",
			"limit" => 3
		));
		
		$this->set(compact("product", "related_products"));
	}
}
